///*
// *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
// *
// *  Redistribution and use in source and binary forms, with or without
// *  modification, are permitted provided that the following conditions are met:
// *
// *  Redistributions of source code must retain the above copyright notice,
// *  this list of conditions and the following disclaimer.
// *  Redistributions in binary form must reproduce the above copyright
// *  notice, this list of conditions and the following disclaimer in the
// *  documentation and/or other materials provided with the distribution.
// *  Neither the name of the dreamlu.net developer nor the names of its
// *  contributors may be used to endorse or promote products derived from
// *  this software without specific prior written permission.
// *  Author: Chill 庄骞 (smallchill@163.com)
// */
//package com.plian.system.service.dp.impl;
//
//import com.alibaba.fastjson.JSONObject;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.plian.Tools.*;
//import com.plian.Tools.office.WordUtil;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.entity.dp.ProductionSafetyAccidents;
//import com.plian.system.entity.dp.ResponsiblePerson;
//import com.plian.system.mapper.dp.ProductionSafetyAccidentsMapper;
//import com.plian.system.model.CommonCode;
//import com.plian.system.model.R;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.mybatis.search.SearchEntity;
//import com.plian.system.mybatis.search.SearchParamEntiy;
//import com.plian.system.mybatis.support.Condition;
//import com.plian.system.service.dp.IProductionSafetyAccidentsService;
//import com.plian.system.service.dp.IResponsiblePersonService;
//import com.plian.system.service.sys.code.IFormCodeService;
//import com.plian.system.service.wf.FormWorkflowService;
//import com.plian.system.vo.dp.ProductionSafetyAccidentsVO;
//import com.plian.system.vo.dp.ResponsiblePersonVO;
//import com.plian.system.wrapper.dp.ProductionSafetyAccidentsWrapper;
//import com.plian.system.wrapper.dp.ResponsiblePersonWrapper;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.core.env.Environment;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//
///**
// * 生产安全事故问题 服务实现类
// *
// * @author jianglei
// * @since 2019-12-05
// */
//@Slf4j
//@Service
//@AllArgsConstructor
//public class ProductionSafetyAccidentsServiceImpl extends BaseServiceImpl<ProductionSafetyAccidentsMapper, ProductionSafetyAccidents> implements IProductionSafetyAccidentsService, BaseFlowService {
//
//	private IResponsiblePersonService responsiblePersonService;
//
//	private FormWorkflowService formWorkflowService;
//
//	private IFormCodeService formCodeService;
//
//	private Environment environment;
//
//	private ProductionSafetyAccidentsWrapper productionSafetyAccidentsWrapper;
//
//	private ResponsiblePersonWrapper responsiblePersonWrapper;
//
//	@Override
//	public boolean saveOrUpdate(ProductionSafetyAccidents productionSafetyAccidents) {
//		if (productionSafetyAccidents.getId() == null) {
//			productionSafetyAccidents.setCode(formCodeService.getCode(FormTypeConstant.DP_PARTY_ACCOUNTABLE_FORM));
//			productionSafetyAccidents.setFormType(String.valueOf(FormTypeConstant.DP_PRODUCTION_SAFETY_ACCIDENTS_FORM));
//			productionSafetyAccidents.setVersion("1");
//		}
//		if (!Optional.ofNullable(productionSafetyAccidents.getStatus()).isPresent()) {
//			productionSafetyAccidents.setStatus(FormStatusConstant.UNREVIEWED);
//		}
//		return super.saveOrUpdate(productionSafetyAccidents);
//	}
//
//	@Override
//	@Transactional(rollbackFor=RuntimeException.class)
//	public boolean deleteLogic(List<Long> ids) {
//		for (Long id : ids) {
//			ProductionSafetyAccidents productionSafetyAccidents = getById(id);
//			if (productionSafetyAccidents == null) {
//				return false;
//			} else if (productionSafetyAccidents.getStatus() != null &&
//					(productionSafetyAccidents.getStatus() != FormStatusConstant.STASH && productionSafetyAccidents.getStatus() != FormStatusConstant.UNREVIEWED)) {
//				return false;
//			}
//			formWorkflowService.deleteProcessInstance(String.valueOf(id));
//		}
//		responsiblePersonService.deleteLogicByProductionSafetyAccidentsId(ids);
//		return super.deleteLogic(ids);
//	}
//
//	@Override
//	public R<ProductionSafetyAccidentsVO> getDetailObj(ProductionSafetyAccidentsVO productionSafetyAccidentsVO) {
//		if(!Optional.ofNullable(productionSafetyAccidentsVO).isPresent()){
//			return new R(CommonCode.FAIL);
//		}
//		productionSafetyAccidentsVO.setResponsiblePersonVOS(responsiblePersonWrapper.entityToVO(responsiblePersonService.list(
//				new LambdaQueryWrapper<ResponsiblePerson>()
//				.eq(ResponsiblePerson::getProductionSafetyAccidentsId,productionSafetyAccidentsVO.getId()))));
//		R<ProductionSafetyAccidentsVO> objResult = new R<>(CommonCode.SUCCESS);
//		objResult.setPageData(productionSafetyAccidentsVO);
//		return objResult;
//	}
//
//	@Override
//	public File exportExcel(JSONObject jsonObject) {
//		List<SearchEntity> entityList = Optional.ofNullable(jsonObject.getJSONArray("query"))
//				.map(x -> x.toJavaList(SearchEntity.class)).orElse(new ArrayList<>());
//		QueryWrapper<ProductionSafetyAccidents> qw = SearchParamEntiy.getQueryWrapper(
//				Condition.getQueryWrapper(new ProductionSafetyAccidents()), entityList
//		);
//
//		List<ProductionSafetyAccidents> floors = list(qw);
////		return ExcelUtils.exportExcelByList(jsonObject, ProductionSafetyAccidentsWrapper.build().listVO(floors));
//		return null;
//	}
//
//	@Override
//	public HashMap<String,Object> commit(String id) {
//		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
//
//		//将需要提交的流程变量返回，用于工作流侧
//		return new HashMap<String,Object>();
//	}
//
//	@Override
//	public Boolean finish(String id) {
//		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
//	}
//
//	@Override
//	public Boolean reject(String id, int formState, String comment) {
//		return handleStatus(Long.valueOf(id), formState);
//	}
//
//	@Override
//	@Transactional(rollbackFor=RuntimeException.class)
//	public Boolean submit(ProductionSafetyAccidents productionSafetyAccidents) {
//		boolean result = saveOrUpdate(productionSafetyAccidents);
//		List<ResponsiblePerson> responsiblePersonList = productionSafetyAccidents.getResponsiblePersonList();
//		if (CollectionUtil.isNotEmpty(responsiblePersonList)) {
//			/**
//			 * 责任人员信息（不包括行政处罚人员）实体类
//			 */
//			List<Long> delIds = responsiblePersonList.stream().filter(responsiblePerson ->
//					Optional.ofNullable(responsiblePerson.getIsDeleted()).isPresent() && responsiblePerson.getIsDeleted() == 1)
//					.map(ResponsiblePerson::getId).collect(Collectors.toList());
//			if (CollectionUtil.isNotEmpty(delIds)) {
//				responsiblePersonService.deleteLogic(delIds);
//			}
//
//			responsiblePersonList.removeIf(responsiblePerson -> (Optional.ofNullable(responsiblePerson.getIsDeleted()).isPresent()
//					&& responsiblePerson.getIsDeleted() == 1));
//
//
//			if (CollectionUtil.isNotEmpty(responsiblePersonList)) {
//				/**
//				 * 给新增数据赋值
//				 */
//				responsiblePersonList.stream().filter(responsiblePerson -> responsiblePerson.getId() == null)
//						.forEach(responsiblePerson -> {
//							responsiblePerson.setProductionSafetyAccidentsId(productionSafetyAccidents.getId());
//							responsiblePerson.setStatus(FormStatusConstant.UNREVIEWED);
//							responsiblePerson.setIsDeleted(0);
//						});
//				responsiblePersonService.saveOrUpdateBatch(responsiblePersonList);
//			}
//		}
//		return result;
//	}
//
//	@Override
//	public File buildword(Long id, HttpServletResponse response) {
//		ProductionSafetyAccidentsVO bean = productionSafetyAccidentsWrapper.entityToVO(getById(id));
//
//		File file = null;
//		try {
//			if (bean != null) {
//				Map<String, Object> data = new HashMap<>(16);
//				data.put("fillingUnitId", bean.getFillingUnitName());
//				if (Optional.ofNullable(bean.getFillingDate()).isPresent()) {
//					data.put("fillingDate", DateUtil.format(bean.getFillingDate(), "yyyy年M月"));
//				}
//				data.put("accidentName", bean.getAccidentName());
//				data.put("accidentLevel", bean.getAccidentLevel());
//				data.put("occurrenceTime", DateUtil.formatDate(bean.getOccurrenceTime()));
//				data.put("takePlace", bean.getTakePlace());
//				data.put("deathNumber", bean.getDeathNumber());
//				data.put("injuredNumber", bean.getInjuredNumber());
//				data.put("directEconomicLoss", bean.getDirectEconomicLoss().doubleValue());
//				data.put("accidentCategories", bean.getAccidentCategories());
//				data.put("caseTime", DateUtil.formatDate(bean.getCaseTime()));
//				data.put("closingTime", DateUtil.formatDate(bean.getClosingTime()));
//				data.put("accountabilityNumber", bean.getAccountabilityNumber());
//				data.put("disciplineNumber", bean.getDisciplineNumber());
//				data.put("otherAccountabilityNumber", bean.getOtherAccountabilityNumber());
//				data.put("businessRulesNumber", bean.getBusinessRulesNumber());
//				data.put("judicialProcessingNumber", bean.getJudicialProcessingNumber());
//
//
//				ResponsiblePerson responsiblePerson = new ResponsiblePerson();
//				responsiblePerson.setProductionSafetyAccidentsId(bean.getId());
//				List<ResponsiblePersonVO> responsiblePersonVOS = responsiblePersonWrapper.entityToVO(responsiblePersonService.list(Condition.getQueryWrapper(responsiblePerson)));
//
//				if (CollectionUtil.isNotEmpty(responsiblePersonVOS)) {
//					data.put("responsiblePersonVOS", responsiblePersonVOS);
//				}
//				String realPath = environment.getProperty("doc.path")  + id + ".doc";
//				file = WordUtil.generateWord(data, realPath , "productionSafetyAccidents.doc","productionSafetyAccidents.ftl");
//				response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
//				InputStream inputStream = new FileInputStream(file);
//				// 激活下载操作
//				OutputStream os = response.getOutputStream();
//				// 循环写入输出流
//				byte[] b = new byte[2048];
//				int length;
//				while ((length = inputStream.read(b)) > 0) {
//					os.write(b, 0, length);
//				}
//				// 这里主要关闭。
//				os.close();
//				inputStream.close();
//			}
//
//		} catch (Exception e) {
//			log.error(ExceptionUtils.getFullStackTrace(e));
//		}
//		return file;
//	}
//
//	@Override
//	public List<PageData> findByIds(List<String> formIds) {
//		QueryWrapper<ProductionSafetyAccidents> queryWrapper = new QueryWrapper<>();
//		queryWrapper.in("id", Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
//		List<ProductionSafetyAccidents> productionSafetyAccidents = list(queryWrapper);
//		List<ProductionSafetyAccidentsVO> productionSafetyAccidentsVOS = productionSafetyAccidentsWrapper.entityToVO(productionSafetyAccidents);
//		List<PageData> pageDataList = new ArrayList<>();
//		try{
//			if (CollectionUtil.isNotEmpty(productionSafetyAccidentsVOS)){
//				for (ProductionSafetyAccidentsVO vo : productionSafetyAccidentsVOS){
//					PageData pd = new PageData();
//					pd.put("id", vo.getId());
//					pd.put("UNITNAME", vo.getFillingUnitName());
//					pd.put("APPLICANTNAME", vo.getCreateUserName());
//					pd.put("applicantId", vo.getCreateUser());
//					pd.put("applyOrganizationId", vo.getFillingUnitId());
//					pd.put("formType", FormTypeConstant.DP_PRODUCTION_SAFETY_ACCIDENTS_FORM);
//					pd.put("orgName", vo.getFillingUnitName());
//					pageDataList.add(pd);
//				}
//			}
//
//			return pageDataList;
//		} catch (Exception e) {
//			log.error(ExceptionUtils.getFullStackTrace(e));
//		}
//		return pageDataList;
//	}
//
//	@Override
//	public List<Integer> getFormType() {
//		return Arrays.asList(FormTypeConstant.DP_PRODUCTION_SAFETY_ACCIDENTS_FORM);
//	}
//
//	@Override
//	public void goBackToStash(String formId) {
//		handleStatus(Long.valueOf(formId), UNREVIEWED);
//	}
//
//	/**
//	 * 统一处理状态机事件方法
//	 *
//	 * @param id          主键
//	 * @param updateStatus  更新状态
//	 * @return boolean
//	 */
//	private Boolean handleStatus(Long id, int updateStatus) {
//		try {
//			ProductionSafetyAccidents productionSafetyAccidents = getById(id);
//			/**
//			 * 设置审批人和审批时间
//			 */
//			if (updateStatus == FormStatusConstant.FINISH){
//				productionSafetyAccidents.setApprovedUser(TokenUtil.getTokenUserId());
//				Date now = DateUtil.now();
//				productionSafetyAccidents.setApprovedTime(now);
//			}
//			productionSafetyAccidents.setStatus(updateStatus);
//			updateById(productionSafetyAccidents);
//			return true;
//		} catch (Exception e) {
//			log.error(ExceptionUtils.getFullStackTrace(e));
//			return false;
//		}
//	}
//}
